from django import http
from django.http import HttpResponseNotFound
from django.http import HttpResponseServerError
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.contents.utils import get_categories
from apps.goods.models import GoodsCategory, SKU
from apps.goods.utils import get_breadcrumb
from utils.response_code import RETCODE


class ListView(View):
    def get(self,request, category_id, page_num):
        categories=get_categories()

        category=GoodsCategory.objects.get(id=category_id)
        breadcrumb=get_breadcrumb(category_id)

        sort=request.GET.get('sort')

        if sort=='hot':
            sort_field='-sales'
        elif sort=='price':
            sort_field='price'
        else:
            sort_field='create_time'

        skus=SKU.objects.filter(category_id=category_id,is_launched=True).order_by(sort_field)

        from django.core.paginator import Paginator
        paginator=Paginator(skus,5)

        total_page=paginator.num_pages

        page_skus=paginator.page(page_num)

        context={
            'categories':categories,
            'breadcrumb':breadcrumb,
            'sort':sort,
            'category':category,
            'page_skus':page_skus,
            'total_page':total_page,
            'page_num':page_num
        }

        return render(request,'list.html',context)


class HotView(View):
    def get(self,request,category_id):
        # 5. 热销排行

        # 1.获取-sales 前两个
        skus = SKU.objects.filter(is_launched=True).order_by('-sales')[:2]

        # 2.构建前端需要的数据格式
        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,
                'name': sku.name,
                'price': sku.price
            })

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'hot_skus': hot_skus})


class DetailView(View):
    def get(self, request, sku_id):

        """提供商品详情页"""
        # 获取当前sku的信息
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return render(request, '404.html')

        # 查询商品频道分类
        categories = get_categories()
        # 查询面包屑导航
        breadcrumb = get_breadcrumb(sku.category_id)

        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.sku_set.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            # 用于形成规格参数-sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')

        print("spec_sku_map",spec_sku_map)
        print("goods_specs",goods_specs)
        print("goods_specs--typt:", type(goods_specs) )
        print("-" * 80)
        print("goods_specs->0", goods_specs[0])
        print("goods_specs->1", goods_specs[1])
        print("-"*80)
        print("sku_key",sku_key)

        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            print("-" * 80)
            # 复制当前sku的规格键
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))
                # 获取每个选项的sku信息
                _sku = SKU.objects.get(id=option.sku_id)
                # 给选项设置库存
                option.stock = _sku.stock
                option.is_launched = _sku.is_launched
                print("option:", option,"option_sku_id:",option.sku_id,"   tuple(key):", tuple(key))
                print("spec_options:",spec_options)
            spec.spec_options = spec_options

        # 渲染页面
        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': goods_specs,
        }
        return render(request, 'detail.html', context)

class DetailVisitView(View):
    """详情页分类商品访问量"""

    def post(self, request, category_id):
        try:
            # 1.获取当前商品
            category = GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            return HttpResponseNotFound('缺少必传参数')

        # 2.查询日期数据
        from datetime import datetime
        # 将日期按照格式转换成字符串
        today_str = datetime.now().strftime('%Y-%m-%d')
        # 将字符串再转换成日期格式
        today_date = datetime.strptime(today_str, '%Y-%m-%d')

        from apps.goods.models import GoodsVisitCount
        try:
            # 3.如果有当天商品分类的数据  就累加数量
            count_data = category.goodsvisitcount_set.get(date=today_date)
        except:
            # 4. 没有, 就新建之后在增加
            count_data = GoodsVisitCount()

        try:
            count_data.count += 1
            count_data.category = category
            count_data.save()
        except Exception as e:
            return HttpResponseServerError('新增失败')

        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})